package WorkTest;


import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyList<T extends Object>  {
    final int define_size=10;

    Object[] arrays=new Object[define_size];
    Lock lock=new ReentrantLock();
    volatile int index=0;
    MyList (int size){
        arrays=new Object[size];
    }
    MyList(){}
    /*添加*/
    synchronized boolean  put(T t){
        /*如果容器容量不足，增大1倍*/
        if(index>=arrays.length){
            resize();
        }
        /*检查重复，重复插入失败，不报错，返回false*/
        if(index!=0){
            for (int i = 0; i <=index ; i++) {
                if(arrays[i]==t){
                    return false;
                }
            }
        }


        arrays[index++]=t;
        return true;

    }
    void resize(){
        Object[] temp=new Object[arrays.length*2];
        int i=0;
        for(Object o:arrays){
            temp[i++]=o;
        }
        arrays=temp;
    }
    /*查询*/
    synchronized T get(int i) throws Exception {
        if(i>index||i<0)throw new Exception("Not Found");
        return (T)arrays[i];
    }
    /*删除*/
    synchronized T remove(int i) throws Exception {
        if(i>index||i<0)throw new Exception("Not Found");
        T oldValue=(T)arrays[i];
        if(i!=arrays.length-1){
        System.arraycopy(arrays,i+1,arrays,i,arrays.length-i-1);
        }else {
            arrays[i]=null;
        }
        index--;
        return oldValue;

    }
    /*修改：设置序号i的值为t*/
    synchronized T set(T t,int i)throws Exception{
        if(i>index||i<0)throw new Exception("Not Found");
        T oldValue=(T)arrays[i];
        arrays[i]=t;
        return oldValue;
    }

    @Override
    public String toString() {
        Object[] temp=new Object[index];
        System.arraycopy(arrays,0,temp,0,index);
        return "MyList{" +
                "arrays=" + Arrays.toString(temp) +
                '}';
    }
}
